package com.borqsprocessmanager.sample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.util.Log;

import com.borqsprocessmanager.ConfigParams;
import com.borqsprocessmanager.info.ProcessStatsInfo;

public class NetWorkSampleMoudle implements ASampleMoudle {
    private final String TAG = "NetWorkSampleMoudle";

    private PackageManager pm;

    private ArrayList<ProcessStatsInfo> preList;

    private static boolean isSampleSystemPricess = false;

    public NetWorkSampleMoudle(Context context) {
        pm = context.getPackageManager();
    }

    @Override
    public ArrayList<ProcessStatsInfo> sample(int sample_id, int type,
            HashMap<String, ProcessStatsInfo> whiteMap) {
        Log.v(TAG, "sample");
        ArrayList<ProcessStatsInfo> resList = null;
        ArrayList<ProcessStatsInfo> cruList = getNetWorkStats(sample_id, pm,
                whiteMap);
        switch (type) {
        case TYPE_GETDATA_AND_CONTINUE:
            resList = getResNetworkStats(preList, cruList);
            Log.v(TAG, "resList.size===" + resList.size());
        case TYPE_CONTINUE:
            preList = cruList;
            break;
        }
        return resList;
    }

    @Override
    public ArrayList<ProcessStatsInfo> getSampleRes() {
        return null;
    }

    private ArrayList<ProcessStatsInfo> getResNetworkStats(
            ArrayList<ProcessStatsInfo> preList,
            ArrayList<ProcessStatsInfo> cruList) {
        ArrayList<ProcessStatsInfo> res = new ArrayList<ProcessStatsInfo>();
        if (preList != null && preList.size() > 0) {
            int preSize = preList.size();
            int cruSize = cruList.size();
            for (int i = 0; i < cruSize; i++) {
                ProcessStatsInfo cruInfo = cruList.get(i);
                String curName = cruInfo.getAppName();
                for (int j = 0; j < preSize; j++) {
                    ProcessStatsInfo preInfo = preList.get(j);
                    String preName = preInfo.getAppName();
                    if (curName.equals(preName)
                            && (cruInfo.total - preInfo.total) > ConfigParams.NETWORK_BASELINE) {
                        ProcessStatsInfo resInfo = new ProcessStatsInfo();
                        resInfo.sampleId = cruInfo.sampleId;
                        resInfo.uid = cruInfo.uid;
                        resInfo.isSystem = cruInfo.isSystem;
                        resInfo.icon = cruInfo.icon;
                        resInfo.packageName = cruInfo.packageName;
                        resInfo.processName = cruInfo.processName;
                        resInfo.appName = cruInfo.appName;
                        resInfo.rx = cruInfo.rx - preInfo.rx;
                        resInfo.tx = cruInfo.tx - preInfo.tx;
                        resInfo.total = cruInfo.total - preInfo.total;
                        res.add(resInfo);
                        break;
                    }
                }
            }
        }
        return res;
    }

    private ArrayList<ProcessStatsInfo> getNetWorkStats(int sampleId,
            PackageManager pm, HashMap<String, ProcessStatsInfo> whiteMap) {
        int isSystem;
        int uid;
        int icon;
        long rx;
        long tx;
        long totalx;
        String packageName;
        String processName;
        String appName;

        ArrayList<ProcessStatsInfo> statsList = new ArrayList<ProcessStatsInfo>();
        List<PackageInfo> packinfos = pm
                .getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES
                        | PackageManager.GET_PERMISSIONS);

        for (PackageInfo info : packinfos) {
            packageName = info.applicationInfo.packageName;
            if (whiteMap.containsKey(packageName)) {
                com.borqsprocessmanager.util.Log.v(TAG, "whiteList_"
                        + packageName);
                break;
            }
            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                isSystem = 1; // systemApp　　　
            } else {
                isSystem = 0;
            }
            if (isSystem == 0 || isSampleSystemPricess) { // 设置一个开关“isSampleSystemPricess”，控制是否sample
                                                          // SystemProcee
                String[] premissions = info.requestedPermissions;
                if (premissions != null && premissions.length > 0) {
                    for (String premission : premissions) {
                        if ("android.permission.INTERNET".equals(premission)) {
                            uid = info.applicationInfo.uid;
                            rx = TrafficStats.getUidRxBytes(uid);
                            tx = TrafficStats.getUidTxBytes(uid);

                            if (rx > 0 || tx > 0) {
                                icon = info.applicationInfo.icon;
                                totalx = rx + tx;
                                // boolean isSystem = true;
                                appName = info.applicationInfo.loadLabel(pm)
                                        .toString();
                                processName = info.applicationInfo.processName;
                                // packageName = info.packageName;

                                // if ((info.applicationInfo.flags &
                                // ApplicationInfo.FLAG_SYSTEM) == 0) {
                                // isSystem = false; // no systemApp　　　
                                // } else {
                                // isSystem = true; // systemApp　　　
                                // }

                                // Log.v(TAG, packageName + "的流量信息:");
                                // Log.v(TAG, appName);
                                // Log.v(TAG, "uid=" + uid);
                                // Log.v(TAG, "system=" + isSystem);
                                // Log.v(TAG, "icon=" + icon);
                                // Log.v(TAG, "total_X=" + totalx);
                                // Log.v(TAG, "rx=" + rx);
                                // Log.v(TAG, "tx=" + tx);

                                ProcessStatsInfo stats = new ProcessStatsInfo();
                                stats.setSampleId(sampleId);
                                stats.setIsSystem(isSystem);
                                stats.setPackageName(packageName);
                                stats.setProcessName(processName);
                                stats.setAppName(appName);
                                stats.setIcon(icon);
                                stats.setRx(rx);
                                stats.setTx(tx);
                                stats.setTotal(totalx);
                                stats.setUid(uid);
                                statsList.add(stats);
                            }
                        }
                    }
                }
            }
        }
        return statsList;
    }

    private void savaDb(ArrayList<ProcessStatsInfo> list) {

    }

    // private boolean isMoreThanTheBaseLine() {
    // long totalBytes = TrafficStats.getTotalRxBytes()
    // + TrafficStats.getTotalTxBytes();
    // if (totalBytes > TOTAL_BASELINE) {
    // return true;
    // }
    // return false;
    // }
}
